import { createSlice } from "@reduxjs/toolkit";
import axios from 'axios';
//创建 slice 对象
let slice = createSlice({
  name: "todo",
  initialState: [],
  //reducer 函数的功能
  reducers: {
    init: (state, action) => {
      // state.push({id: 1, title: 'xxx', done: false}, {id: 2, title: 'YYY', done: false})
      //将 action.payload 数组中的元素插入到状态的数组中
      state.push(...action.payload);
      // state = action.payload;// 这样子是不可以的哦
    },
    //新增操作
    add: (state, {payload}) => {
      //新增
      state.push(payload);
    },
    //更新操作
    updateTitle: (state, {payload}) => {
      //循环
      state.forEach(item => {
        //比较
        if(item.id === payload.id){
          //修改标题
          item.title = payload.title
        }
      });
    }
  },
});

//获取 reducer 函数
export default slice.reducer;

//获取 action creator
export let {init, add, updateTitle} = slice.actions;

//声明 selector 回调函数
export let todoSelector = state => state.todo;

//声明异步的 action creator 获取所有的任务
export let asyncGetTodos = () => {
  //返回一个回调函数
  return async dispatch => {
    let result = await axios.get('http://localhost:9000/todo');
    //输出结果 
    //更新 redux 中的状态
    dispatch(init(result.data));// init(result.data)  => {type: 'todo/init', payload: [xx]}
  }
}

export let asyncAddTodo = (title) => {
  return async dispatch => {
    let result = await axios.post('http://localhost:9000/todo', {
      title: title,
      done: false
    });
    //更新 redux 中的状态
    dispatch(add(result.data)); // add(result.data)  => {type: 'todo/add', payload: result.data}
  }
}

//声明异步的 action creator 更新任务的标题
export let asyncUpdateTodoTitle = (id, title) => {
  return async dispatch => {
    let result = await axios.patch(`http://localhost:9000/todo/${id}`, {
      title: title
    });
    //更新redux中todo的状态
    dispatch(updateTitle({id,title}));
  }
}